package com.wanli.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wanli.common.Result;
import com.wanli.domain.entity.Category;
import com.wanli.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.wanli.common.BaseController;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController extends BaseController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping("/update")
    public Result update(@RequestBody Category category) {
        category.setUpdated(LocalDateTime.now());
        categoryService.updateById(category);
        return Result.success("分类数据更新成功");
    }

    @GetMapping("/getById/{categoryId}")
    public Result getById(@PathVariable Integer categoryId) {
        Category category = categoryService.getById(categoryId);
        return Result.success(category);
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody String[] categoryIds) {
        // Arrays.asList(数组) 将数组转化为 List集合
        categoryService.removeByIds(Arrays.asList(categoryIds));
        return Result.success("分类信息删除成功");
    }

    // 获得所有分类信息，不分页
    @GetMapping("/all")
    public Result all() {
        List<Category> list = categoryService.list();
        return Result.success(list);
    }

    // 接口，显示所有商家分类信息
    @GetMapping("/list")
    public Result list(String categoryName) {
        Page<Category> categoryList = categoryService.page(getPage(),
                new QueryWrapper<Category>
                        ().like(StrUtil.isNotBlank(categoryName), "category_name", categoryName));
        return Result.success(categoryList);
    }

    @PostMapping("/save")
    public Result save(@RequestBody Category category) {
        if (category.getCategoryCover() == null || category.getCategoryCover().length() < 0) {
            // 如果上传图片为空，给默认的
            category.setCategoryCover("https://alextachalova.com/wp-content/themes/wp-wellow/assets/images/no-image.jpg");
        }
        category.setCreated(LocalDateTime.now());
        category.setUpdated(LocalDateTime.now());
        categoryService.save(category);
        return Result.success("保存信息成功");
    }

    /**
     * 获取各种类餐品数
     * @return
     */
    @GetMapping("/count")
    public Result getCategoryCount() {
        return categoryService.getCategoryCount();
    }
}